package com.futvan.z.framework.util;

import java.security.Security;
import java.util.Arrays;
import java.util.HashMap;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

import com.alibaba.fastjson.JSONObject;
import com.futvan.z.framework.common.bean.Code;
import com.futvan.z.framework.common.bean.Result;
import com.futvan.z.framework.core.z;

import sun.misc.BASE64Decoder;

/**
 * 微信工具类
 * @author zz
 *
 */
public class WeiXinUtil {


	/**
	 * 解析encryptedData获取手机号码
	 * @param session_key
	 * @param encryptedData
	 * @param iv
	 * @return
	 */
	public static Result getUserPhoneNumber(String session_key,String encryptedData,String iv) {
		Result result = new Result();
		if(z.isNotNull(session_key)) {
			if(z.isNotNull(encryptedData)) {
				if(z.isNotNull(iv)) {
					try {
						BASE64Decoder decoder = new BASE64Decoder();
						byte[] raw = decoder.decodeBuffer(session_key);
						SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
						IvParameterSpec ivParameter = new IvParameterSpec(decoder.decodeBuffer(iv));
						Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
						cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivParameter);
						byte[] myendicod = decoder.decodeBuffer(encryptedData);
						byte[] original = cipher.doFinal(myendicod);
						String originalString = new String(original, "UTF-8");
						HashMap json = JsonUtil.getObject(originalString, HashMap.class);
						if(z.isNotNull(json) && z.isNotNull(json.get("phoneNumber"))) {
							result.setCode(Code.SUCCESS);
							result.setMsg("ok");
							result.setData(json.get("phoneNumber"));
						}else {
							result.setCode(Code.ERROR);
							result.setMsg("解析 encryptedData 出错,未找到电话号码 ");
						}
					} catch (Exception ex) {
						result.setCode(Code.ERROR);
						result.setMsg("解析 encryptedData 出错|"+ex.getMessage());
					}
				}else {
					result.setCode(Code.ERROR);
					result.setMsg("iv is null");
				}
			}else {
				result.setCode(Code.ERROR);
				result.setMsg("encryptedData is null");
			}
		}else {
			result.setCode(Code.ERROR);
			result.setMsg("session_key is null");
		}
		return result;
	}

	/**
	 * 	获取OpenId 用户唯一标识     session_key会话密钥
	 * @param appid
	 * @param secret
	 * @param js_code
	 * @return
	 */
	public static Result jscode2session(String appid,String secret,String js_code) {
		Result result = new Result();
		if(z.isNotNull(appid)) {
			if(z.isNotNull(secret)) {
				if(z.isNotNull(js_code)) {
					HashMap<String,String> parameters = new HashMap<String,String>();
					parameters.put("appid", appid);
					parameters.put("secret", secret);
					parameters.put("js_code", js_code);
					parameters.put("grant_type", "authorization_code");
					String txt = HttpUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", parameters);
					if(z.isNotNull(txt)) {
						HashMap json = new HashMap();
						try {
							json = JSONObject.parseObject(txt, HashMap.class);
							if(z.isNotNull(json) && z.isNotNull(json.get("openid"))) {
								//根据OpenId获取客户zid
								String custom_zid = z.getSqlSession().selectOne("selectone", "SELECT zid FROM crm_customer WHERE wechat_openid = '"+json.get("openid")+"'");
								if(z.isNotNull(custom_zid)) {
									json.put("zid", custom_zid);
									result.setCode(Code.SUCCESS);
									result.setMsg("ok");
									result.setData(json);
								}else {
									result.setCode(Code.SUCCESS);
									result.setMsg("ok but zid is null");
									result.setData(json);
								}
							}else {
								result.setCode(Code.ERROR);
								result.setMsg("微信：jscode2session接口返回内容错误|返回值:"+txt);
							}

						} catch (Exception e) {
							result.setCode(Code.ERROR);
							result.setMsg("微信：jscode2session接口返回内容无法转换成json数据|返回值 ："+txt);
						}

					}else {
						result.setCode(Code.ERROR);
						result.setMsg("微信：jscode2session接口返回为空");
					}


				}else {
					result.setCode(Code.ERROR);
					result.setMsg("js_code is null");
				}
			}else {
				result.setCode(Code.ERROR);
				result.setMsg("secret is null");
			}
		}else {
			result.setCode(Code.ERROR);
			result.setMsg("appid is null");
		}
		return result;
	}
}
